package com.hktf.corelib.utils;

import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.List;

public class GsonUtils {
	private static Gson gson;
	static{
		gson = new Gson();
	}
	/**
	 * 
	 * 将json串转换成对象
	 * @param jsonResult
	 * @param clz
	 * @return
	 */
	public static<T> T jsonToBean(String jsonResult,Class<T> clz){
		if(gson==null){
			gson = new Gson();
		}
		T t = gson.fromJson(jsonResult, clz);
		 return t;
	}
	
	/**
	 * 
	 * 对象   to json
	 * @param object
	 * @return
	 */
	public static String createGsonString(Object object) {
		if(gson==null){
			gson = new Gson();
		}
		String gsonString = gson.toJson(object);
		return gsonString;
	}

	/**
	 * 
	 * 将json转换成list  读取数据流
	 * @param gsonString
	 * @param cls
	 * @return
	 */
	public static <T> List<T> GsonToList(String gsonString, Type typeOfT) {
		if(gson==null){
			gson = new Gson();
		}
		List<T> list = gson.fromJson(gsonString, typeOfT);
		return list;
	}
	
	
	
	
//	public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
//		if(gson==null){
//			gson = new Gson();
//		}
//		List<T> list = gson.fromJson(gsonString, new TypeToken<List<T>>() {}.getType());
//		return list;
//	}
	
	/**
	 * 
	 * list转换成json   存数据流
	 * @param lists
	 * @return
	 */
	public static <T> String ListToJson(List<T> lists){
		if(gson==null){
			gson = new Gson();
		}
		String str = gson.toJson(lists); 
		return str;
	}
	
	
	
}
